package me.younian.transmit;

import org.apache.log4j.Logger;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;


public class TransPortData extends Thread {
    private static final Logger logger = Logger.getLogger(TransPortData.class);

    ServerSocket getDataSocket;
    ServerSocket putDataSocket;
    SocketServerClient socketServerClient;
    String type;

    public TransPortData(ServerSocket getDataSocket, ServerSocket putDataSocket, SocketServerClient socketServerClient, String type) {
        this.getDataSocket = getDataSocket;
        this.putDataSocket = putDataSocket;
        this.socketServerClient = socketServerClient;
        this.type = type;
    }

    public void run() {
        while (true) {
            try {
                //这里每次请求的Socket不一样，所以需要一直accept
                Socket getSocket = getDataSocket.accept();
                InputStream in = getSocket.getInputStream();
                //读入数据
                byte[] data = new byte[1024];
                int readlen = in.read(data);
                //如果没有数据，则暂停
                if (readlen > 0) {
                    Socket client = socketServerClient.getClient();
                    if (client == null) {
                        logger.error("Client Off Line, Waiting ....");
                        Thread.sleep(3000);
                        continue;
                    }
                    logger.info("Transmit: " + readlen + "  " + getSocket.getInetAddress() + ":" + getSocket.getPort() + "-->" + client.getInetAddress() + ":" + client.getPort());
                    OutputStream out = client.getOutputStream();
                    out.write(data, 0, readlen);
                    out.flush();

                    try {
                        InputStream in2 = client.getInputStream();
                        byte[] data2 = new byte[1024];
                        int readlen2 = in2.read(data2);
                        StringBuilder stringBuilder = new StringBuilder();
                        while (readlen2 > 0) {
                            String str = new String(data2);
                            if (str.contains("##EOF##")) {
                                str = str.substring(0, str.indexOf("##EOF##"));
                                stringBuilder.append(str);
                                break;
                            }
                            stringBuilder.append(str);
                            readlen2 = in2.read(data2);
                        }
                        if (!stringBuilder.toString().equals(""))
                            reponse(getSocket, stringBuilder.toString().getBytes(), stringBuilder.length());

                    } catch (SocketTimeoutException s) {
                        s.printStackTrace();
                    } catch (SocketException e) {
                        logger.error("Client updated.... wait...");
                        e.printStackTrace();
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e1) {
                            e1.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            } catch (Exception e) {
                logger.error("Client updated.... wait...");
                e.printStackTrace();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            } finally {
                //关闭socket
                /*try {
                    if (putDataSocket != null) {
                        putDataSocket.close();
                    }
                } catch (Exception exx) {
                    exx.printStackTrace();
                }
                try {
                    if (getDataSocket != null) {
                        getDataSocket.close();
                    }
                } catch (Exception exx) {
                    exx.printStackTrace();
                }*/
            }
        }
    }

    private void reponse(Socket client, byte[] content, int size) {
        try {
            PrintStream writer = new PrintStream(client.getOutputStream());
            writer.println("HTTP/1.0 200 OK");// 返回应答消息,并结束应答
            writer.println("Content-Type:text/html");
            writer.println("Content-Length:" + content.length);// 返回内容字节数
            writer.println();// 根据 HTTP 协议, 空行将结束头信息

            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
